package com.client.util;

import com.Emplyment.entity.Article;
import com.Emplyment.entity.QuestionBank;
import com.Emplyment.util.CacheHotCompany;
import com.Emplyment.util.CacheInterview;
import com.client.mapper.ArticleMapper;
import com.client.mapper.QuestionBankMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Slf4j
public class QuestionCallable implements Callable<String> {

    private RedisTemplate redisTemplate;

    private QuestionBankMapper questionBankMapper;

    private Integer questionId;

    private static final String INTERVIEW_HASH_KEY = "interview:HASH:data";

    public QuestionCallable(QuestionBankMapper questionBankMapper, RedisTemplate redisTemplate, Integer questionId){
        this.questionBankMapper = questionBankMapper;
        this.redisTemplate = redisTemplate;
        this.questionId = questionId;
    }

    @Override
    public String call() throws Exception {
        QuestionBank hotQuestion = questionBankMapper.getQuestionById(questionId);
        CacheInterview cacheInterview = new CacheInterview();
        long expireTime = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(2);
        //如果数据为空那么添加一个空的数据解决缓存穿透问题
        if (hotQuestion!= null) {
            cacheInterview.setQuestionBank(hotQuestion);
            cacheInterview.setExpireTime(expireTime);
            ObjectMapper mapper = new ObjectMapper();
            String questionJSON = mapper.writeValueAsString(cacheInterview);
            redisTemplate.opsForHash().put(INTERVIEW_HASH_KEY, questionId, questionJSON);
            log.info("缓存添加成功:{}",questionJSON);
        }
        return null;
    }
}
